package testing;
import java.io.*;
import java.security.MessageDigest;

import encodingSimulation.EncodingHelper;
import encodingSimulation.EncodingImplementation;

public class MD5Checksum {

   public static byte[] createChecksum(File filename) throws Exception {
       InputStream fis =  new FileInputStream(filename);

       byte[] buffer = new byte[1024];
       MessageDigest complete = MessageDigest.getInstance("MD5");
       int numRead;	
//       EncodingImplementation e= new EncodingImplementation();
       EncodingHelper e = new EncodingHelper();
       StringBuffer fileData = e.readFile(filename);
       int max=fileData.toString().getBytes().length/1024;
//       System.out.println(" "+max);
       int i=0;
       do {
    	   int startPos=i* 1024;
    	   int endpos = startPos+1024;
    	   numRead = endpos-startPos;
    	  buffer= fileData.substring(startPos, endpos).toString().getBytes();
//           numRead = fis.read(buffer);
//           System.out.println(" "+ new String(buffer));
//           System.out.println(" "+ numRead);
           if (numRead > 0) {
               complete.update(buffer, 0, numRead);
//               System.out.println(" "+ complete.toString());
           }
           i=i+1;
       } while (numRead != -1 && i<max);

       fis.close();
       return complete.digest();
   }

   // see this How-to for a faster way to convert
   // a byte array to a HEX string
   public static String getMD5Checksum(File filename) throws Exception {
       byte[] b = createChecksum(filename);
       String result = new String() ;
//       System.out.println(" "+result);

       for (int i=0; i < b.length; i++) {
           result += Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
       }
       return result;
   }

   public static void main(String args[]) {
       try {
    	   File filename = new File("C:" + File.separator + "Users"
   				+ File.separator + "Bhavya" + File.separator + "Desktop"
   				+ File.separator + "java_for_cloudcomputing" + File.separator
   				+ "java_code" + File.separator + "ObtainedSample.txt.txt");
           System.out.println(getMD5Checksum(filename));
           File filename1 = new File("C:" + File.separator + "Users"
      				+ File.separator + "Bhavya" + File.separator + "Desktop"
      				+ File.separator + "java_for_cloudcomputing" + File.separator
      				+ "java_code" + File.separator + "ObtainedSample1.txt.txt");
           System.out.println(getMD5Checksum(filename1));
           // output :
           //  0bb2827c5eacf570b6064e24e0e6653b
           // ref :
           //  http://www.apache.org/dist/
           //          tomcat/tomcat-5/v5.5.17/bin
           //              /apache-tomcat-5.5.17.exe.MD5
           //  0bb2827c5eacf570b6064e24e0e6653b *apache-tomcat-5.5.17.exe
       }
       catch (Exception e) {
           e.printStackTrace();
       }
   }
}
